<?php
class weebUIAllocineSearch
{
    /**
    * Runs the search
    **/
    function run()
    {
        $searchURL = 'http://www.allocine.fr/recherche/?rub=1&motcle=' . urlencode( $this->query );
        $searchPage = file_get_contents( $searchURL );

        $searchPage = substr( $searchPage, strpos( $searchPage, '<h3><b>Films <h4>' ) );
        $searchPage = substr( $searchPage, 0, strpos( $searchPage, '<h3><b>', 1 ) );

        // @todo match more details (year, director, actors, image)
        if ( preg_match_all( '#<a href="/film/fichefilm_gen_cfilm=(?:[0-9]+)\.html"><img src="(http://.+?\.(?:jpg|gif))" .*?</a></td><td valign="top"><h4><a href="(/film/fichefilm_gen_cfilm=([0-9]+)\.html)" class="link1">(.*?)</a>.*?<h4 style="[^"]*">([0-9]{4})</h4>.*?<h5 style="[^"]*">de ([^<]+)</h5>#', $searchPage, $matches, PREG_SET_ORDER ) )
        {
            foreach ( $matches as $match )
            {
                $item = new weebUIAllocineItem();
                $item->title = strip_tags( $match[4] );
                $item->id = $match[3];
                $item->by = $match[6];
                $item->year = $match[5];
                $item->cover = $match[1];

                if ( strtolower( $movieTitle ) == strtolower( $query ) )
                {
                    $this->bestMatch = $item;
                }
                $this->results[] = $item;
            }
            if ( !$this->bestMatch ) $this->bestMatch = $this->results[ count( $this->results ) - 1 ];
        }
        else throw new weebUIAllocineSearchNoResultsException( $this->query );
    }

    /**
    * @var string
    **/
    public $query;

    /**
    * @var array of weebUIAllocineItem
    **/
    public $results;

    /**
     * @var weebUIAllocineItem
     **/
    public $bestMatch = false;
}
?>